<template>
  <div class="purchase-container">
    <!-- 搜索框：筛选条件与后端返回字段严格对齐 -->
    <el-form :inline="true" :model="filters" class="search-form" label-width="100px">
      <el-form-item label="采购单号：">
        <el-input 
          v-model="filters.purchaseCode" 
          clearable 
          style="width: 200px;"
        />
      </el-form-item>

      <el-form-item label="供应商：">
        <el-input 
          v-model="filters.supplier" 
          clearable 
          style="width: 200px;"
        />
      </el-form-item>

      <el-form-item label="采购日期：">
        <el-date-picker
          type="date"
          v-model="filters.beginDate"
          clearable
          placeholder="起始日期"
          style="margin-right: 10px;"
        />
        <el-date-picker
          type="date"
          v-model="filters.endDate"
          placeholder="截止日期"
          clearable
        />
      </el-form-item>

      <el-form-item label="产品品类：">
        <el-input 
          v-model="filters.category" 
          clearable 
          style="width: 200px;"
        />
      </el-form-item>

      <el-form-item label="采购人：">
        <el-input 
          v-model="filters.purchaseUser" 
          clearable 
          style="width: 200px;"
        />
      </el-form-item>

      <el-form-item label="入库状态：">
        <el-select 
          v-model="filters.storeStatus" 
          clearable 
          style="width: 200px;"
        >
          <el-option label="未入库" value="1"></el-option>
          <el-option label="部分入库" value="2"></el-option>
          <el-option label="已入库" value="3"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="conditionQuery">查询</el-button>
        <el-button @click="resetFilters" style="margin-left: 10px;">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格-->
    <el-table 
      :data="tableData" 
      style="width: 100%" 
      stripe 
      border 
      empty-text="暂无采购单数据"
      :header-cell-style="{ background: '#f5f7fa' }"
    >
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="purchaseCode" label="采购单号" width="180" align="center" />
      <el-table-column prop="supplier" label="供应商名称" width="180" align="center" />
      <el-table-column prop="category" label="产品品类" width="180" align="center" />
      <el-table-column prop="purchaseDate" label="采购日期" width="180" align="center" />
      <el-table-column prop="purchaseUser" label="采购人" width="180" align="center" />
      <el-table-column prop="storeStatus" label="入库状态" width="180" align="center">
        <template v-slot="{ row }">
          {{ statusMap[row.storeStatus] || '未知状态' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template v-slot="{ row }">
          <el-button type="primary" @click="toDetail(row.id)">到货登记</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <el-pagination 
      background 
      layout="sizes,total,prev,pager,next,jumper" 
      :total="total" 
      class="pagination" 
      :page-size="pageSize"
      :current-page="page"
      :page-sizes="[3,5, 10, 20]"
      @current-change="handlePageChange"
      @size-change="handleSizeChange"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { queryPurchase } from '@/api/arrival/purchase.js';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

// 1. 响应式数据：
const tableData = ref([]); // 采购单列表
const total = ref(0);      // 总记录数
const page = ref(1);       // 当前页
const pageSize = ref(5);   // 每页条数

// 2. 筛选条件
const filters = ref({
  purchaseCode: undefined, 
  supplier: undefined,      
  beginDate: undefined,    
  endDate: undefined,       
  category: undefined,     
  purchaseUser: undefined,
  storeStatus: undefined
});

// 3. 路由实例（跳转详情页）
const router = useRouter();

// 4. 入库状态映射：与后端storeStatus值（1/2/3）对应
const statusMap = {
  1: '未入库',
  2: '部分入库',
  3: '已入库'
};

// 5. 工具函数：日期格式化（后端需要YYYY-MM-DD字符串，与返回的purchaseDate格式一致）
const formatDate = (date) => {
  if (!date) return undefined; // 无日期时不传递该参数，避免后端条件干扰
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 补0（如7→07）
  const day = String(date.getDate()).padStart(2, '0');        // 补0（如8→08）
  return `${year}-${month}-${day}`;
};

// 6. 核心请求：调用后端接口，传递筛选+分页参数
const fetchPurchaseList = async () => {
  // 构建请求参数：只传递有值的条件（避免空参数干扰后端查询）
  const requestParams = {
    page: page.value,
    pageSize: pageSize.value,
    // 筛选条件：与后端MyBatis的if判断条件对应（非null/非空字符串才传递）
    /**
    *相当于是：if(filters.value.supplier){
    *  requestParams.supplier=filters.value.supplier
    *}
    */
    ...(filters.value.purchaseCode && { purchaseCode: filters.value.purchaseCode }),
    ...(filters.value.supplier && { supplier: filters.value.supplier }), // 关键：传递supplier而非supplierName
    ...(filters.value.beginDate && { beginDate: formatDate(filters.value.beginDate) }),
    ...(filters.value.endDate && { endDate: formatDate(filters.value.endDate) }),
    ...(filters.value.category && { category: filters.value.category }),
    ...(filters.value.purchaseUser && { purchaseUser: filters.value.purchaseUser }),
    ...(filters.value.storeStatus !== undefined && { storeStatus: filters.value.storeStatus })
  };

  try {
    const res = await queryPurchase(requestParams);
    // 匹配后端返回格式（code=200表示成功）
    if (res.code === 200) {
      tableData.value = res.data.list; // 赋值采购单列表
      total.value = res.data.total;     // 赋值总记录数
      page.value = res.data.page;       // 同步当前页（避免前后端页码不一致）
      pageSize.value = res.data.pageSize; // 同步每页条数
    } else {
      ElMessage.error(`查询失败：${res.msg || '未知错误'}`);
    }
  } catch (error) {
    ElMessage.error('接口请求异常，请检查网络或后端服务');
    console.error('请求错误详情：', error);
  }
};

// 7. 分页事件处理
const handlePageChange = (newPage) => {
  page.value = newPage;
  fetchPurchaseList(); // 重新请求当前页数据
};

// 每页条数改变
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  page.value = 1; // 条数改变时重置为第1页
  fetchPurchaseList();
};

// 8. 筛选查询与重置
// 点击“查询”按钮
const conditionQuery = () => {
  page.value = 1; // 筛选条件改变时，从第1页开始查询
  fetchPurchaseList();
};

// 点击“重置”按钮
const resetFilters = () => {
  Object.keys(filters.value).forEach(key => {
    filters.value[key] = undefined;
  });
  page.value = 1; // 重置为第1页
  fetchPurchaseList(); // 重新请求全部数据
};

// 9. 跳转到货登记详情页（携带采购单ID）
const toDetail = (id) => {
  router.push({ 
    path: '/arrival/detail', 
    query: { id } // 传递采购单ID（后端需要通过ID查询详情）
  });
};

// 10. 页面挂载时初始化：请求第1页的采购单数据
onMounted(() => {
  fetchPurchaseList();
});
</script>

<style scoped>
.purchase-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.search-form {
  margin-bottom: 20px;
  padding: 15px;
  background: #f9fafb;
  border-radius: 6px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>